package com.sunrise.xdoc.security;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * TODO: This bean should be in session scope. It's initialized when user login, destroyed when logout.
 * 
 */
@Transactional
public class SecurityVoter implements ISecurityVoter {
    @Autowired
    private SecurityCached securityCached;

    @Override
    public boolean checkFunction(String functionCode, String functionMode) {
        Set<FunctionMode> accessibleMode = securityCached.getAccessibleMode(functionCode);
        if (accessibleMode != null) {
            return accessibleMode.containsAll(FunctionMode.toFuntionMode(functionMode));
        } else {
            return false;
        }
    }

    public SecurityCached getSecurityCached() {
        return securityCached;
    }

    public void setSecurityCached(SecurityCached securityCached) {
        this.securityCached = securityCached;
    }

    @Override
    public boolean checkKey(String key, String functionMode) {
        if (key.equals("http://localhost:8080/xdoc-web/") || key.contains("pages/index.jsf")
                || key.contains("pages/loginView.jsf")) {
            // Always accept these page
            return true;
        }
        securityCached.refreshSecurity(); // will remove after finish, add to login process
        // TODO: This is for testing only. Must adapt it !!!!!
        return checkFunction("XEM_LIST_HOA_DON", functionMode);
    }

}
